package com.android.chessgame;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.android.chessgame.view.GameBoardView;

import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * 蓝牙对战页面
 */
public class GameActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "GameActivity";

    private static final int[][] images = new int[][]{
            {R.drawable.map_chess_02, R.drawable.map_chess_03, R.drawable.map_chess_04, R.drawable.map_chess_05, R.drawable.map_chess_06, R.drawable.map_chess_07, R.drawable.map_chess_08, R.drawable.map_chess_09, R.drawable.map_chess_10},
            {R.drawable.map_chess_11, R.drawable.map_chess_12, R.drawable.map_chess_13, R.drawable.map_chess_14, R.drawable.map_chess_15, R.drawable.map_chess_16, R.drawable.map_chess_17, R.drawable.map_chess_18, R.drawable.map_chess_19},
            {R.drawable.map_chess_20, R.drawable.map_chess_21, R.drawable.map_chess_22, R.drawable.map_chess_23, R.drawable.map_chess_24, R.drawable.map_chess_25, R.drawable.map_chess_26, R.drawable.map_chess_27, R.drawable.map_chess_28},
            {R.drawable.map_chess_29, R.drawable.map_chess_30, R.drawable.map_chess_31, R.drawable.map_chess_32, R.drawable.map_chess_33, R.drawable.map_chess_34, R.drawable.map_chess_35, R.drawable.map_chess_36, R.drawable.map_chess_37},
            {R.drawable.map_chess_38, R.drawable.map_chess_39, R.drawable.map_chess_40, R.drawable.map_chess_41, R.drawable.map_chess_42, R.drawable.map_chess_43, R.drawable.map_chess_44, R.drawable.map_chess_45, R.drawable.map_chess_46},
            {R.drawable.map_chess_47, R.drawable.map_chess_48, R.drawable.map_chess_49, R.drawable.map_chess_50, R.drawable.map_chess_51, R.drawable.map_chess_52, R.drawable.map_chess_53, R.drawable.map_chess_54, R.drawable.map_chess_55},
            {R.drawable.map_chess_56, R.drawable.map_chess_57, R.drawable.map_chess_58, R.drawable.map_chess_59, R.drawable.map_chess_60, R.drawable.map_chess_61, R.drawable.map_chess_62, R.drawable.map_chess_63, R.drawable.map_chess_64},
            {R.drawable.map_chess_65, R.drawable.map_chess_66, R.drawable.map_chess_67, R.drawable.map_chess_68, R.drawable.map_chess_69, R.drawable.map_chess_70, R.drawable.map_chess_71, R.drawable.map_chess_72, R.drawable.map_chess_73},
            {R.drawable.map_chess_74, R.drawable.map_chess_75, R.drawable.map_chess_76, R.drawable.map_chess_77, R.drawable.map_chess_78, R.drawable.map_chess_79, R.drawable.map_chess_80, R.drawable.map_chess_81, R.drawable.map_chess_82},
            {R.drawable.map_chess_83, R.drawable.map_chess_84, R.drawable.map_chess_85, R.drawable.map_chess_86, R.drawable.map_chess_87, R.drawable.map_chess_88, R.drawable.map_chess_89, R.drawable.map_chess_90, R.drawable.map_chess_91},

    };


    private RecyclerView recyclerView;
    private StaggeredGridLayoutManager staggeredGridLayoutManager;
    private List<ModelList> list;
    private MyAdapter myAdapter;
    private boolean isMove = false;//是否移动

    private ModelList modelListFirst;//上一次选中的棋子
    private int positionFirst;//上一次的下标

    private LinearLayout llBluetooth;
    private Button btnSearch;

    private BluetoothAdapter mBluetoothAdapter;
    private ListView lvDevices;
    private List<String> bluetoothDevices = new ArrayList<String>();
    private ArrayAdapter<String> arrayAdapter;
    private final UUID MY_UUID = UUID.fromString("abcd1234-ab12-ab12-ab12-abcdef123456");//随便定义一个
    private BluetoothSocket clientSocket;
    private BluetoothDevice device;
    private OutputStream os;//输出流


    //    private BluetoothAdapter mBluetoothAdapter;
    private AcceptThread acceptThread;
    //    private final UUID MY_UUID = UUID.fromString("abcd1234-ab12-ab12-ab12-abcdef123456");//和客户端相同的UUID
    private final String NAME = "Bluetooth_Socket";
    private BluetoothServerSocket serverSocket;
    private BluetoothSocket socket;
    private InputStream is;//输入流

    private String address;

    private boolean isWaiting = true;//当消息发出去后需要等对方的消息 当执行完一步后，需要等等对方执行

    private ProgressDialog progressDialog = null;

    private Map<Integer, ModelList[]> modelListMapBlue;//记录蓝方棋路

    private Map<Integer, ModelList[]> modelListMapRed;//记录红方棋路

    private Button btnBack;
    private GameBoardView mGameBoardView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        llBluetooth = (LinearLayout) findViewById(R.id.llBluetooth);
        btnSearch = (Button) findViewById(R.id.btnSearch);

        lvDevices = (ListView) findViewById(R.id.lvDevices);
        mGameBoardView = (GameBoardView) findViewById(R.id.ly_board);

        btnSearch.setOnClickListener(this);

        requestBluetoothPermission();

    }

    //初始化蓝牙信息并且开启蓝牙服务
    private void initBluetooth() {
        if (mBluetoothAdapter != null) {

            acceptThread = new AcceptThread();
            acceptThread.start();

            //获取已经配对的蓝牙设备
            Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice device : pairedDevices) {
                    bluetoothDevices.add(device.getName() + ":" + device.getAddress());
                }
            }
            arrayAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, android.R.id.text1, bluetoothDevices);
            lvDevices.setAdapter(arrayAdapter);
            lvDevices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String s = arrayAdapter.getItem(position);
                    address = s.substring(s.indexOf(":") + 1).trim();//把地址解析出来
                    showProDialog();
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                                Toast.makeText(GameActivity.this, "连接失败！", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }, 10000);
                    //主动连接蓝牙服务端
                    try {
                        //判断当前是否正在搜索
                        if (mBluetoothAdapter.isDiscovering()) {
                            mBluetoothAdapter.cancelDiscovery();
                        }
                        try {
                            if (device == null) {
                                //获得远程设备
                                device = mBluetoothAdapter.getRemoteDevice(address);
                            }
                            if (clientSocket == null) {
                                //创建客户端蓝牙Socket
                                clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                                //开始连接蓝牙，如果没有配对则弹出对话框提示我们进行配对
                                clientSocket.connect();
                                //获得输出流（客户端指向服务端输出文本）
                                os = clientSocket.getOutputStream();
                            }
                        } catch (Exception e) {
                        }
                        if (os != null) {
                            //往服务端写信息
                            String message = "请求" + getBluetoothAddress();
//                        Log.e(TAG,"onItemClick--message="+message);
                            os.write(message.getBytes("utf-8"));
                        }
                    } catch (Exception e) {
                    }

                }
            });


            // 设置广播信息过滤
            IntentFilter filter = new IntentFilter();
            filter.addAction(BluetoothDevice.ACTION_FOUND);//每搜索到一个设备就会发送一个该广播
            filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);//当全部搜索完后发送该广播
            filter.setPriority(Integer.MAX_VALUE);//设置优先级
            // 注册蓝牙搜索广播接收者，接收并处理搜索结果
            this.registerReceiver(receiver, filter);

        }
    }

    /**
     * 初始化数据
     */
    private void initData() {
        modelListMapBlue = new HashMap<>();
        modelListMapRed = new HashMap<>();
        list = new ArrayList<>();
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 10; j++) {
                ModelList modelList = new ModelList();
//                modelList.setMapImage(images[j][i]);
                modelList.setPieceType(0);
                modelList.setX(i);
                modelList.setY(j);
                list.add(modelList);
            }
        }

        //红方
        list.get(0).setPieces(Pieces.車);
        list.get(0).setPieceImage(R.drawable.che_r);
        list.get(0).setPieceType(2);

        list.get(10).setPieces(Pieces.馬);
        list.get(10).setPieceImage(R.drawable.ma_r);
        list.get(10).setPieceType(2);

        list.get(20).setPieces(Pieces.象);
        list.get(20).setPieceImage(R.drawable.xiang_r);
        list.get(20).setPieceType(2);

        list.get(30).setPieces(Pieces.士);
        list.get(30).setPieceImage(R.drawable.shi_r);
        list.get(30).setPieceType(2);

        list.get(40).setPieces(Pieces.帅);
        list.get(40).setPieceImage(R.drawable.shuai_r);
        list.get(40).setPieceType(2);

        list.get(50).setPieces(Pieces.士);
        list.get(50).setPieceImage(R.drawable.shi_r);
        list.get(50).setPieceType(2);

        list.get(60).setPieces(Pieces.象);
        list.get(60).setPieceImage(R.drawable.xiang_r);
        list.get(60).setPieceType(2);

        list.get(70).setPieces(Pieces.馬);
        list.get(70).setPieceImage(R.drawable.ma_r);
        list.get(70).setPieceType(2);

        list.get(80).setPieces(Pieces.車);
        list.get(80).setPieceImage(R.drawable.che_r);
        list.get(80).setPieceType(2);

        list.get(12).setPieces(Pieces.炮);
        list.get(12).setPieceImage(R.drawable.pao_r);
        list.get(12).setPieceType(2);

        list.get(72).setPieces(Pieces.炮);
        list.get(72).setPieceImage(R.drawable.pao_r);
        list.get(72).setPieceType(2);

        for (int i = 0; i < 5; i++) {
            list.get(3 + i * 20).setPieces(Pieces.兵);
            list.get(3 + i * 20).setPieceImage(R.drawable.bing_r);
            list.get(3 + i * 20).setPieceType(2);
        }


        //蓝方
        list.get(9).setPieces(Pieces.車);
        list.get(9).setPieceImage(R.drawable.che_b);
        list.get(9).setPieceType(1);

        list.get(19).setPieces(Pieces.馬);
        list.get(19).setPieceImage(R.drawable.ma_b);
        list.get(19).setPieceType(1);

        list.get(29).setPieces(Pieces.象);
        list.get(29).setPieceImage(R.drawable.xiang_b);
        list.get(29).setPieceType(1);

        list.get(39).setPieces(Pieces.士);
        list.get(39).setPieceImage(R.drawable.shi_b);
        list.get(39).setPieceType(1);

        list.get(49).setPieces(Pieces.帅);
        list.get(49).setPieceImage(R.drawable.jiang_b);
        list.get(49).setPieceType(1);

        list.get(59).setPieces(Pieces.士);
        list.get(59).setPieceImage(R.drawable.shi_b);
        list.get(59).setPieceType(1);

        list.get(69).setPieces(Pieces.象);
        list.get(69).setPieceImage(R.drawable.xiang_b);
        list.get(69).setPieceType(1);

        list.get(79).setPieces(Pieces.馬);
        list.get(79).setPieceImage(R.drawable.ma_b);
        list.get(79).setPieceType(1);

        list.get(89).setPieces(Pieces.車);
        list.get(89).setPieceImage(R.drawable.che_b);
        list.get(89).setPieceType(1);

        list.get(17).setPieces(Pieces.炮);
        list.get(17).setPieceImage(R.drawable.pao_b);
        list.get(17).setPieceType(1);

        list.get(77).setPieces(Pieces.炮);
        list.get(77).setPieceImage(R.drawable.pao_b);
        list.get(77).setPieceType(1);

        for (int i = 0; i < 5; i++) {
            list.get(6 + i * 20).setPieces(Pieces.兵);
            list.get(6 + i * 20).setPieceImage(R.drawable.zu_b);
            list.get(6 + i * 20).setPieceType(1);
        }

    }

    /**
     * 红方，即对手
     */
    private void initDataHong() {
        modelListMapBlue = new HashMap<>();
        modelListMapRed = new HashMap<>();
        list = new ArrayList<>();
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 10; j++) {
                ModelList modelList = new ModelList();
//                modelList.setMapImage(images[j][i]);
                modelList.setPieceType(0);
                modelList.setX(i);
                modelList.setY(j);
                list.add(modelList);
            }
        }

        //蓝放
        list.get(0).setPieces(Pieces.車);
        list.get(0).setPieceImage(R.drawable.che_b);
        list.get(0).setPieceType(1);

        list.get(10).setPieces(Pieces.馬);
        list.get(10).setPieceImage(R.drawable.ma_b);
        list.get(10).setPieceType(1);

        list.get(20).setPieces(Pieces.象);
        list.get(20).setPieceImage(R.drawable.xiang_b);
        list.get(20).setPieceType(1);

        list.get(30).setPieces(Pieces.士);
        list.get(30).setPieceImage(R.drawable.shi_b);
        list.get(30).setPieceType(1);

        list.get(40).setPieces(Pieces.帅);
        list.get(40).setPieceImage(R.drawable.jiang_b);
        list.get(40).setPieceType(1);

        list.get(50).setPieces(Pieces.士);
        list.get(50).setPieceImage(R.drawable.shi_b);
        list.get(50).setPieceType(1);

        list.get(60).setPieces(Pieces.象);
        list.get(60).setPieceImage(R.drawable.xiang_b);
        list.get(60).setPieceType(1);

        list.get(70).setPieces(Pieces.馬);
        list.get(70).setPieceImage(R.drawable.ma_b);
        list.get(70).setPieceType(1);

        list.get(80).setPieces(Pieces.車);
        list.get(80).setPieceImage(R.drawable.che_b);
        list.get(80).setPieceType(1);

        list.get(12).setPieces(Pieces.炮);
        list.get(12).setPieceImage(R.drawable.pao_b);
        list.get(12).setPieceType(1);

        list.get(72).setPieces(Pieces.炮);
        list.get(72).setPieceImage(R.drawable.pao_b);
        list.get(72).setPieceType(1);

        for (int i = 0; i < 5; i++) {
            list.get(3 + i * 20).setPieces(Pieces.兵);
            list.get(3 + i * 20).setPieceImage(R.drawable.zu_b);
            list.get(3 + i * 20).setPieceType(1);
        }


        //红方
        list.get(9).setPieces(Pieces.車);
        list.get(9).setPieceImage(R.drawable.che_r);
        list.get(9).setPieceType(2);

        list.get(19).setPieces(Pieces.馬);
        list.get(19).setPieceImage(R.drawable.ma_r);
        list.get(19).setPieceType(2);

        list.get(29).setPieces(Pieces.象);
        list.get(29).setPieceImage(R.drawable.xiang_r);
        list.get(29).setPieceType(2);

        list.get(39).setPieces(Pieces.士);
        list.get(39).setPieceImage(R.drawable.shi_r);
        list.get(39).setPieceType(2);

        list.get(49).setPieces(Pieces.帅);
        list.get(49).setPieceImage(R.drawable.shuai_r);
        list.get(49).setPieceType(2);

        list.get(59).setPieces(Pieces.士);
        list.get(59).setPieceImage(R.drawable.shi_r);
        list.get(59).setPieceType(2);

        list.get(69).setPieces(Pieces.象);
        list.get(69).setPieceImage(R.drawable.xiang_r);
        list.get(69).setPieceType(2);

        list.get(79).setPieces(Pieces.馬);
        list.get(79).setPieceImage(R.drawable.ma_r);
        list.get(79).setPieceType(2);

        list.get(89).setPieces(Pieces.車);
        list.get(89).setPieceImage(R.drawable.che_r);
        list.get(89).setPieceType(2);

        list.get(17).setPieces(Pieces.炮);
        list.get(17).setPieceImage(R.drawable.pao_r);
        list.get(17).setPieceType(2);

        list.get(77).setPieces(Pieces.炮);
        list.get(77).setPieceImage(R.drawable.pao_r);
        list.get(77).setPieceType(2);

        for (int i = 0; i < 5; i++) {
            list.get(6 + i * 20).setPieces(Pieces.兵);
            list.get(6 + i * 20).setPieceImage(R.drawable.bing_r);
            list.get(6 + i * 20).setPieceType(2);
        }

    }


    private void initView() {
        LinearLayout llMenu = (LinearLayout) findViewById(R.id.llMenu);
        llMenu.setVisibility(View.VISIBLE);
        btnBack = (Button) findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        staggeredGridLayoutManager = new StaggeredGridLayoutManager(10, StaggeredGridLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(staggeredGridLayoutManager);
        myAdapter = new MyAdapter(this, list);
        recyclerView.setAdapter(myAdapter);

        myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (isWaiting) {
                    Toast.makeText(GameActivity.this, "等待对方执行", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (isMove) {
                    ModelList modelList = list.get(position);
                    if (modelList.getPieceType() != modelListFirst.getPieceType()) {
                        if (modelListFirst.getPieces() == Pieces.車) {

                            if (modelList.getX() == modelListFirst.getX() || modelList.getY() == modelListFirst.getY()) {
                                if (cheLogic(modelList, position)) {
                                    moveEnd(modelList, position);
                                }

                            }
                        } else if (modelListFirst.getPieces() == Pieces.馬) {
                            int dx = Math.abs(modelList.getX() - modelListFirst.getX());
                            int dy = Math.abs(modelList.getY() - modelListFirst.getY());
                            if ((dx == 2 && dy == 1) || (dx == 1 && dy == 2)) {
                                if (maLogic(modelList, position)) {
                                    moveEnd(modelList, position);
                                }

                            }

                        } else if (modelListFirst.getPieces() == Pieces.象) {
                            int dx = Math.abs(modelList.getX() - modelListFirst.getX());
                            int dy = Math.abs(modelList.getY() - modelListFirst.getY());
                            if (flag == 1) {
                                if (modelListFirst.getPieceType() == 1) {
                                    if (dx == 2 && dy == 2 && modelList.getY() >= 5) {
                                        if (xiangLogic(modelList, position)) {
                                            moveEnd(modelList, position);
                                        }

                                    }
                                } else if (modelListFirst.getPieceType() == 2) {
                                    if (dx == 2 && dy == 2 && modelList.getY() <= 4) {
                                        if (xiangLogic(modelList, position)) {
                                            moveEnd(modelList, position);
                                        }

                                    }
                                }
                            } else if (flag == 2) {
                                if (modelListFirst.getPieceType() == 1) {
                                    if (dx == 2 && dy == 2 && modelList.getY() <= 4) {
                                        if (xiangLogic(modelList, position)) {
                                            moveEnd(modelList, position);
                                        }

                                    }
                                } else if (modelListFirst.getPieceType() == 2) {
                                    if (dx == 2 && dy == 2 && modelList.getY() >= 5) {
                                        if (xiangLogic(modelList, position)) {
                                            moveEnd(modelList, position);
                                        }

                                    }
                                }
                            }


                        } else if (modelListFirst.getPieces() == Pieces.士) {
                            int dx = Math.abs(modelList.getX() - modelListFirst.getX());
                            int dy = Math.abs(modelList.getY() - modelListFirst.getY());
                            if (flag == 1) {
                                if (modelListFirst.getPieceType() == 1) {
                                    if (dx == 1 && dy == 1 && (modelList.getX() > 2 && modelList.getX() < 7) && modelList.getY() > 6) {
                                        moveEnd(modelList, position);
                                    }
                                } else if (modelListFirst.getPieceType() == 2) {
                                    if (dx == 1 && dy == 1 && (modelList.getX() > 2 && modelList.getX() < 7) && modelList.getY() < 3) {
                                        moveEnd(modelList, position);
                                    }
                                }
                            } else if (flag == 2) {
                                if (modelListFirst.getPieceType() == 1) {
                                    if (dx == 1 && dy == 1 && (modelList.getX() > 2 && modelList.getX() < 7) && modelList.getY() < 3) {
                                        moveEnd(modelList, position);
                                    }
                                } else if (modelListFirst.getPieceType() == 2) {
                                    if (dx == 1 && dy == 1 && (modelList.getX() > 2 && modelList.getX() < 7) && modelList.getY() > 6) {
                                        moveEnd(modelList, position);
                                    }
                                }
                            }


                        } else if (modelListFirst.getPieces() == Pieces.帅) {

                            int dx = Math.abs(modelList.getX() - modelListFirst.getX());
                            int dy = Math.abs(modelList.getY() - modelListFirst.getY());
                            if (flag == 1) {
                                if (modelListFirst.getPieceType() == 1) {
                                    if ((dx + dy == 1) && (modelList.getX() > 2 && modelList.getX() < 7) && modelList.getY() > 6) {
                                        moveEnd(modelList, position);
                                    } else {
                                        if (modelList.getPieces() == Pieces.帅) {
                                            if (shuaiLogic(modelList, position)) {
                                                moveEnd(modelList, position);
                                            }
                                        }
                                    }
                                } else if (modelListFirst.getPieceType() == 2) {
                                    if ((dx + dy == 1) && (modelList.getX() > 2 && modelList.getX() < 7) && modelList.getY() < 3) {
                                        moveEnd(modelList, position);
                                    } else {
                                        if (modelList.getPieces() == Pieces.帅) {
                                            if (shuaiLogic(modelList, position)) {
                                                moveEnd(modelList, position);
                                            }
                                        }
                                    }
                                }
                            } else if (flag == 2) {
                                if (modelListFirst.getPieceType() == 1) {
                                    if ((dx + dy == 1) && (modelList.getX() > 2 && modelList.getX() < 7) && modelList.getY() < 3) {
                                        moveEnd(modelList, position);
                                    } else {
                                        if (modelList.getPieces() == Pieces.帅) {
                                            if (shuaiLogic(modelList, position)) {
                                                moveEnd(modelList, position);
                                            }
                                        }
                                    }
                                } else if (modelListFirst.getPieceType() == 2) {
                                    if ((dx + dy == 1) && (modelList.getX() > 2 && modelList.getX() < 7) && modelList.getY() > 6) {
                                        moveEnd(modelList, position);
                                    } else {
                                        if (modelList.getPieces() == Pieces.帅) {
                                            if (shuaiLogic(modelList, position)) {
                                                moveEnd(modelList, position);
                                            }
                                        }
                                    }
                                }
                            }

                        } else if (modelListFirst.getPieces() == Pieces.炮) {
                            if (modelList.getX() == modelListFirst.getX() || modelList.getY() == modelListFirst.getY()) {
                                if (paoLogic(modelList, position)) {
                                    moveEnd(modelList, position);
                                }
                            }

                        } else if (modelListFirst.getPieces() == Pieces.兵) {
                            int dx = Math.abs(modelList.getX() - modelListFirst.getX());
                            int dy = Math.abs(modelList.getY() - modelListFirst.getY());
                            if (flag == 1) {
                                if (modelListFirst.getPieceType() == 1) {

                                    if (modelListFirst.getY() > 4) {
                                        if (modelList.getX() == modelListFirst.getX() && modelList.getY() - modelListFirst.getY() == -1) {
                                            moveEnd(modelList, position);
                                        }
                                    } else {
                                        if (dx + dy == 1 && modelList.getY() - modelListFirst.getY() <= 0) {
                                            moveEnd(modelList, position);
                                        }
                                    }

                                } else if (modelListFirst.getPieceType() == 2) {
                                    if (modelListFirst.getY() < 5) {
                                        if (modelList.getX() == modelListFirst.getX() && modelList.getY() - modelListFirst.getY() == 1) {
                                            moveEnd(modelList, position);
                                        }
                                    } else {
                                        if (dx + dy == 1 && modelList.getY() - modelListFirst.getY() >= 0) {
                                            moveEnd(modelList, position);
                                        }
                                    }
                                }
                            } else if (flag == 2) {
                                if (modelListFirst.getPieceType() == 1) {

                                    if (modelListFirst.getY() < 5) {
                                        if (modelList.getX() == modelListFirst.getX() && modelList.getY() - modelListFirst.getY() == 1) {
                                            moveEnd(modelList, position);
                                        }
                                    } else {
                                        if (dx + dy == 1 && modelList.getY() - modelListFirst.getY() >= 0) {
                                            moveEnd(modelList, position);
                                        }
                                    }

                                } else if (modelListFirst.getPieceType() == 2) {
                                    if (modelListFirst.getY() > 4) {
                                        if (modelList.getX() == modelListFirst.getX() && modelList.getY() - modelListFirst.getY() == -1) {
                                            moveEnd(modelList, position);
                                        }
                                    } else {
                                        if (dx + dy == 1 && modelList.getY() - modelListFirst.getY() <= 0) {
                                            moveEnd(modelList, position);
                                        }
                                    }
                                }
                            }


                        }
                    } else {
                        if (list.get(position).getPieceType() != 0) {
                            //改变上一个的状态
                            list.get(positionFirst).setSel(false);
                            myAdapter.notifyItemChanged(positionFirst);
                            //记录选中棋子的信息并且改变状态
                            modelListFirst = list.get(position);
                            positionFirst = position;
                            isMove = true;
                            list.get(position).setSel(true);
                            myAdapter.notifyItemChanged(position);
                        }
                    }

                } else {

                    if (list.get(position).getPieceType() != 0) {

                        if (list.get(position).getPieceType() == flag) {
                            //记录选中棋子的信息并且改变状态
                            modelListFirst = list.get(position);
                            positionFirst = position;
                            isMove = true;
                            list.get(position).setSel(true);
                            myAdapter.notifyItemChanged(position);

                        } else {
                            Toast.makeText(GameActivity.this, "请选择自己的棋子", Toast.LENGTH_SHORT).show();
                        }

                    }
                }

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.btnSearch:
                //如果当前在搜索，就先取消搜索
                if (mBluetoothAdapter.isDiscovering()) {
                    mBluetoothAdapter.cancelDiscovery();
                }
                //开启搜索
                mBluetoothAdapter.startDiscovery();

                break;
            case R.id.btnBack:
                if (isMove) {
                    isMove = false;
                    list.get(positionFirst).setSel(false);
                    myAdapter.notifyItemChanged(positionFirst);

                } else {
                    sendMsg("请求悔棋");
                }

                break;

        }
    }

    /**
     * 移动结束
     *
     * @param modelList 目的地的对象
     * @param position  目的地所对应的下标
     */
    private void moveEnd(ModelList modelList, int position) {

        if (modelList.getPieces() == Pieces.帅) {
            if (modelList.getPieceType() == 1) {

                showGameOverDialog("红方赢了！");
            } else if (modelList.getPieceType() == 2) {

                showGameOverDialog("蓝方赢了！");
            }
        }

        if (!isWaiting) {
            isWaiting = true;
            String msg = (89 - positionFirst) + "," + (89 - position);
            sendMsg(msg);
        } else {
            isWaiting = false;
        }

        if (modelListFirst.getPieceType() == 1) {//记录蓝方棋路
//            Log.e(TAG,"modelListFirst="+modelListFirst+",modelList="+modelList);
            ModelList model1 = getModelList(modelListFirst);
            ModelList model2 = getModelList(modelList);
            modelListMapBlue.put(modelListMapBlue.size() + 1, new ModelList[]{model1, model2});
        } else {//记录红方棋路
            ModelList model1 = getModelList(modelListFirst);
            ModelList model2 = getModelList(modelList);
            modelListMapRed.put(modelListMapRed.size() + 1, new ModelList[]{model1, model2});
        }


        modelList.setPieceImage(modelListFirst.getPieceImage());
        modelList.setPieceType(modelListFirst.getPieceType());
        modelList.setPieces(modelListFirst.getPieces());

        list.get(positionFirst).setPieceType(0);
        list.get(positionFirst).setSel(false);

        list.set(position, modelList);
        myAdapter.notifyItemChanged(positionFirst);
        myAdapter.notifyItemChanged(position);
        isMove = false;

    }

    /**
     * 车的逻辑
     *
     * @param modelList 目的地的对象
     * @param position  目的地所对应的下标
     */
    private boolean cheLogic(ModelList modelList, int position) {
        boolean canGo = true;
        if (modelList.getX() == modelListFirst.getX()) {
            int dy = modelList.getY() - modelListFirst.getY();
            if (dy > 0) {
                for (int i = (modelListFirst.getY() + 1); i < modelList.getY(); i++) {

                    if (list.get(modelListFirst.getX() * 10 + i).getPieceType() != 0) {
                        return false;
                    }
                }
            } else {
                for (int i = (modelList.getY() + 1); i < modelListFirst.getY(); i++) {

                    if (list.get(modelListFirst.getX() * 10 + i).getPieceType() != 0) {
                        return false;
                    }
                }
            }

        }
        if (modelList.getY() == modelListFirst.getY()) {
            int dx = modelList.getX() - modelListFirst.getX();
            if (dx > 0) {
                for (int i = (modelListFirst.getX() + 1); i < modelList.getX(); i++) {

                    if (list.get(i * 10 + modelListFirst.getY()).getPieceType() != 0) {
                        return false;
                    }
                }
            } else {
                for (int i = (modelList.getX() + 1); i < modelListFirst.getX(); i++) {

                    if (list.get(i * 10 + modelListFirst.getY()).getPieceType() != 0) {
                        return false;
                    }
                }
            }
        }

        return canGo;

    }

    /**
     * 馬的逻辑
     *
     * @param modelList 目的地的对象
     * @param position  目的地所对应的下标
     */
    private boolean maLogic(ModelList modelList, int position) {
        boolean canGo = true;
        if (modelList.getX() - modelListFirst.getX() == 2) {
            if (list.get((modelListFirst.getX() + 1) * 10 + modelListFirst.getY()).getPieceType() != 0) {
                canGo = false;
            }
        }

        if (modelList.getX() - modelListFirst.getX() == -2) {
            if (list.get((modelListFirst.getX() - 1) * 10 + modelListFirst.getY()).getPieceType() != 0) {
                canGo = false;
            }
        }

        if (modelList.getY() - modelListFirst.getY() == 2) {
            if (list.get(modelListFirst.getX() * 10 + modelListFirst.getY() + 1).getPieceType() != 0) {
                canGo = false;
            }
        }

        if (modelList.getY() - modelListFirst.getY() == -2) {
            if (list.get(modelListFirst.getX() * 10 + modelListFirst.getY() - 1).getPieceType() != 0) {
                canGo = false;
            }
        }

        return canGo;

    }

    /**
     * 象的逻辑
     *
     * @param modelList 目的地的对象
     * @param position  目的地所对应的下标
     */
    private boolean xiangLogic(ModelList modelList, int position) {
        boolean canGo = true;
        if (modelList.getX() - modelListFirst.getX() > 0 && modelList.getY() - modelListFirst.getY() > 0) {
            int cx = modelListFirst.getX() + 1;
            int cy = modelListFirst.getY() + 1;
            if (list.get(cx * 10 + cy).getPieceType() != 0) {
                canGo = false;
            }
        }

        if (modelList.getX() - modelListFirst.getX() > 0 && modelList.getY() - modelListFirst.getY() < 0) {
            int cx = modelListFirst.getX() + 1;
            int cy = modelListFirst.getY() - 1;
            if (list.get(cx * 10 + cy).getPieceType() != 0) {
                canGo = false;
            }
        }

        if (modelList.getX() - modelListFirst.getX() < 0 && modelList.getY() - modelListFirst.getY() < 0) {
            int cx = modelListFirst.getX() - 1;
            int cy = modelListFirst.getY() - 1;
            if (list.get(cx * 10 + cy).getPieceType() != 0) {
                canGo = false;
            }
        }

        if (modelList.getX() - modelListFirst.getX() < 0 && modelList.getY() - modelListFirst.getY() > 0) {
            int cx = modelListFirst.getX() - 1;
            int cy = modelListFirst.getY() + 1;
            if (list.get(cx * 10 + cy).getPieceType() != 0) {
                canGo = false;
            }
        }

        return canGo;

    }


    /**
     * 帅吃帅的的逻辑
     *
     * @param modelList 目的地的对象
     * @param position  目的地所对应的下标
     */
    private boolean shuaiLogic(ModelList modelList, int position) {
        boolean canGo = true;
        if (modelList.getX() == modelListFirst.getX()) {
            int dy = modelList.getY() - modelListFirst.getY();
            if (dy > 0) {
                for (int i = (modelListFirst.getY() + 1); i < modelList.getY(); i++) {

                    if (list.get(modelListFirst.getX() * 10 + i).getPieceType() != 0) {
                        canGo = false;
                    }
                }
            } else {
                for (int i = (modelList.getY() + 1); i < modelListFirst.getY(); i++) {

                    if (list.get(modelListFirst.getX() * 10 + i).getPieceType() != 0) {
                        canGo = false;
                    }
                }
            }

        } else {
            canGo = false;
        }

        return canGo;

    }


    /**
     * 炮的逻辑
     *
     * @param modelList 目的地的对象
     * @param position  目的地所对应的下标
     */
    private boolean paoLogic(ModelList modelList, int position) {
        boolean canGo = true;
        if (modelList.getPieceType() == 0) {
            if (modelList.getX() == modelListFirst.getX()) {
                int dy = modelList.getY() - modelListFirst.getY();
                if (dy > 0) {
                    for (int i = (modelListFirst.getY() + 1); i < modelList.getY(); i++) {

                        if (list.get(modelListFirst.getX() * 10 + i).getPieceType() != 0) {
                            return false;
                        }
                    }
                } else {
                    for (int i = (modelList.getY() + 1); i < modelListFirst.getY(); i++) {

                        if (list.get(modelListFirst.getX() * 10 + i).getPieceType() != 0) {
                            return false;
                        }
                    }
                }

            }
            if (modelList.getY() == modelListFirst.getY()) {
                int dx = modelList.getX() - modelListFirst.getX();
                if (dx > 0) {
                    for (int i = (modelListFirst.getX() + 1); i < modelList.getX(); i++) {

                        if (list.get(i * 10 + modelListFirst.getY()).getPieceType() != 0) {
                            return false;
                        }
                    }
                } else {
                    for (int i = (modelList.getX() + 1); i < modelListFirst.getX(); i++) {

                        if (list.get(i * 10 + modelListFirst.getY()).getPieceType() != 0) {
                            return false;
                        }
                    }
                }
            }
        } else {
            int sum = 0;
            if (modelList.getX() == modelListFirst.getX()) {
                int dy = modelList.getY() - modelListFirst.getY();
                if (dy > 0) {
                    for (int i = (modelListFirst.getY() + 1); i < modelList.getY(); i++) {

                        if (list.get(modelListFirst.getX() * 10 + i).getPieceType() != 0) {
                            sum++;
                        }
                    }
                } else {
                    for (int i = (modelList.getY() + 1); i < modelListFirst.getY(); i++) {

                        if (list.get(modelListFirst.getX() * 10 + i).getPieceType() != 0) {
                            sum++;
                        }
                    }
                }

            }
            if (modelList.getY() == modelListFirst.getY()) {
                int dx = modelList.getX() - modelListFirst.getX();
                if (dx > 0) {
                    for (int i = (modelListFirst.getX() + 1); i < modelList.getX(); i++) {

                        if (list.get(i * 10 + modelListFirst.getY()).getPieceType() != 0) {
                            sum++;
                        }
                    }
                } else {
                    for (int i = (modelList.getX() + 1); i < modelListFirst.getX(); i++) {

                        if (list.get(i * 10 + modelListFirst.getY()).getPieceType() != 0) {
                            sum++;
                        }
                    }
                }
            }

            if (sum != 1) {
                canGo = false;
            }
        }

        return canGo;

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isMove) {
                isMove = false;
                list.get(positionFirst).setSel(false);
                myAdapter.notifyItemChanged(positionFirst);
                return true;
            }

        }

        return super.onKeyDown(keyCode, event);
    }

    private void showGameOverDialog(String msg) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示：");
        builder.setMessage(msg);
        builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
        builder.setNegativeButton("再来一局", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (flag == 1) {
                    initData();
                    initView();
                } else if (flag == 2) {
                    initDataHong();
                    initView();
                }

            }
        });
        builder.create().show();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBluetoothAdapter.isEnabled()) {
            this.unregisterReceiver(receiver);
        }

    }

    /**
     * 定义广播接收器
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
//                    Log.e(TAG,"已搜索--"+device.getName() + ":" + device.getAddress());
                    bluetoothDevices.add(device.getName() + ":" + device.getAddress());
                    arrayAdapter.notifyDataSetChanged();//更新适配器

                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                //已搜索完成
                Log.e(TAG, "已搜索完成");

            }
        }
    };

    private static final int REQUEST_BLUETOOTH_PERMISSION = 10;

    private void requestBluetoothPermission() {
        //判断系统版本
        if (Build.VERSION.SDK_INT >= 23) {
            //检测当前app是否拥有某个权限
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION);
            //判断这个权限是否已经授权过
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要 向用户解释，为什么要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    Toast.makeText(this, "Need bluetooth permission.", Toast.LENGTH_SHORT).show();
                }
                ActivityCompat.requestPermissions(this, new String[]
                        {Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_BLUETOOTH_PERMISSION);
            } else {
                mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (!mBluetoothAdapter.isEnabled()) {//判断蓝牙是否开启，没有则开启
                    Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enabler, 3);
                } else {
                    initBluetooth();
                }


            }
        } else {
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (!mBluetoothAdapter.isEnabled()) {//判断蓝牙是否开启，没有则开启
                Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enabler, 3);
            } else {
                initBluetooth();
            }

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (permissions.length > 0 && grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (requestCode == 10) {
                    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                    if (!mBluetoothAdapter.isEnabled()) {//判断蓝牙是否开启，没有则开启
                        Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enabler, 3);
                    } else {
                        initBluetooth();
                    }
                }
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 3) {
                if (!mBluetoothAdapter.isEnabled()) {//判断蓝牙是否开启，没有则开启
                    Intent enabler = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(enabler, 3);
                } else {
                    initBluetooth();
                }
            }
        }
    }

    private int flag = 0;//1-蓝放，2-红方

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
//            Toast.makeText(getApplicationContext(), String.valueOf(msg.obj), Toast.LENGTH_LONG).show();
            String meesage = String.valueOf(msg.obj);
//            Log.e(TAG,"meesage="+meesage);
            if (meesage.contains("请求")) {
                address = meesage.substring(2);
//                Log.e(TAG,"address="+address);
                //判断当前是否正在搜索
                if (mBluetoothAdapter.isDiscovering()) {
                    mBluetoothAdapter.cancelDiscovery();
                }
                sendMsg("应答");
                isWaiting = false;
                flag = 1;
                llBluetooth.setVisibility(View.GONE);
                mGameBoardView.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.VISIBLE);
                initData();
                initView();
            } else if (meesage.contains("应答")) {
                flag = 2;
                llBluetooth.setVisibility(View.GONE);
                mGameBoardView.setVisibility(View.VISIBLE);
                recyclerView.setVisibility(View.VISIBLE);
                initDataHong();
                initView();
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                    Toast.makeText(GameActivity.this, "游戏开始，对手先行！", Toast.LENGTH_SHORT).show();
                }

            } else if (meesage.equals("请求悔棋")) {
                sendMsg("答应悔棋");
                back();
            } else if (meesage.equals("答应悔棋")) {
                back();
            } else {
                positionFirst = Integer.parseInt(meesage.split(",")[0]);
                modelListFirst = list.get(positionFirst);
                int position = Integer.parseInt(meesage.split(",")[1]);
                moveEnd(list.get(position), position);
            }
            super.handleMessage(msg);
        }
    };

    //服务端监听客户端的线程类
    private class AcceptThread extends Thread {
        public AcceptThread() {
            try {
                serverSocket = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
            } catch (Exception e) {
            }
        }

        public void run() {
            try {
                socket = serverSocket.accept();
                is = socket.getInputStream();
                while (true) {
                    byte[] buffer = new byte[1024];
                    int count = is.read(buffer);
                    Message msg = new Message();
                    msg.obj = new String(buffer, 0, count, "utf-8");
                    handler.sendMessage(msg);
                }
            } catch (Exception e) {
            }
        }
    }


    private void sendMsg(String msg) {
        Log.e(TAG, "sendMsg--msg=" + msg);
        try {
            if (device == null) {
                //获得远程设备
                device = mBluetoothAdapter.getRemoteDevice(address);
            }
            if (clientSocket == null) {
                //创建客户端蓝牙Socket
                clientSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
                //开始连接蓝牙，如果没有配对则弹出对话框提示我们进行配对
                clientSocket.connect();
                //获得输出流（客户端指向服务端输出文本）
                os = clientSocket.getOutputStream();
            }
            if (os != null) {
                //往服务端写信息
                String message = msg;
                os.write(message.getBytes("utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


    /**
     * 获取蓝牙地址
     *
     * @return
     */
    public static String getBluetoothAddress() {

        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            Field field = bluetoothAdapter.getClass().getDeclaredField("mService");
            // 参数值为true，禁用访问控制检查
            field.setAccessible(true);
            Object bluetoothManagerService = field.get(bluetoothAdapter);
            if (bluetoothManagerService == null) {
                return null;
            }
            Method method = bluetoothManagerService.getClass().getMethod("getAddress");
            Object address = method.invoke(bluetoothManagerService);
            if (address != null && address instanceof String) {

                return (String) address;
            } else {
                return null;
            }

        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }


    private void showProDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("正在匹配对手...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void back() {
        int blue = modelListMapBlue.size();
        int red = modelListMapRed.size();
        Log.e(TAG, "back() returned: blue=" + blue + ",red=" + red);
        if (flag == 1) {//蓝方的悔棋逻辑
            if (blue > 0 || red > 0) {
                if (blue == red) {
                    //红棋回到上一步
                    ModelList red1 = modelListMapRed.get(red)[0];
                    ModelList red2 = modelListMapRed.get(red)[1];
                    int posR1 = red1.getX() * 10 + red1.getY();
                    int posR2 = red2.getX() * 10 + red2.getY();
                    list.set(posR1, red1);
                    list.set(posR2, red2);
                    myAdapter.notifyItemChanged(posR1);
                    myAdapter.notifyItemChanged(posR2);
                    modelListMapRed.remove(red);

                    //蓝棋回到上一步
                    ModelList blue1 = modelListMapBlue.get(blue)[0];
                    ModelList blue2 = modelListMapBlue.get(blue)[1];
                    int posB1 = blue1.getX() * 10 + blue1.getY();
                    int posB2 = blue2.getX() * 10 + blue2.getY();
                    list.set(posB1, blue1);
                    list.set(posB2, blue2);
                    myAdapter.notifyItemChanged(posB1);
                    myAdapter.notifyItemChanged(posB2);
                    modelListMapBlue.remove(blue);

                    //重制到蓝棋先走
                    isMove = false;

                } else if (blue > red) {

                    //蓝棋回到上一步
                    ModelList blue1 = modelListMapBlue.get(blue)[0];
                    ModelList blue2 = modelListMapBlue.get(blue)[1];
//                Log.e(TAG,"blue1="+blue1.toString()+",blue2="+blue2.toString());
                    int posB1 = blue1.getX() * 10 + blue1.getY();
                    int posB2 = blue2.getX() * 10 + blue2.getY();
                    list.set(posB1, blue1);
                    list.set(posB2, blue2);
//                Log.e(TAG,"blue1="+blue1+",blue2="+blue2);
                    myAdapter.notifyItemChanged(posB1);
                    myAdapter.notifyItemChanged(posB2);
                    modelListMapBlue.remove(blue);

                    //重制到棋先走
                    isMove = false;
                }
            } else {

            }
        } else if (flag == 2) {//红方的悔棋逻辑
            if (blue > 0 || red > 0) {
                if (blue == red) {
                    //红棋回到上一步
                    ModelList red1 = modelListMapRed.get(red)[0];
                    ModelList red2 = modelListMapRed.get(red)[1];
                    int posR1 = red1.getX() * 10 + red1.getY();
                    int posR2 = red2.getX() * 10 + red2.getY();
                    list.set(posR1, red1);
                    list.set(posR2, red2);
                    myAdapter.notifyItemChanged(posR1);
                    myAdapter.notifyItemChanged(posR2);
                    modelListMapRed.remove(red);

                    //恢复到蓝棋先走
                    isMove = false;

                } else if (blue > red && red > 0) {

                    //蓝棋回到上一步
                    ModelList blue1 = modelListMapBlue.get(blue)[0];
                    ModelList blue2 = modelListMapBlue.get(blue)[1];
//                Log.e(TAG,"blue1="+blue1.toString()+",blue2="+blue2.toString());
                    int posB1 = blue1.getX() * 10 + blue1.getY();
                    int posB2 = blue2.getX() * 10 + blue2.getY();
                    list.set(posB1, blue1);
                    list.set(posB2, blue2);
//                Log.e(TAG,"blue1="+blue1+",blue2="+blue2);
                    myAdapter.notifyItemChanged(posB1);
                    myAdapter.notifyItemChanged(posB2);
                    modelListMapBlue.remove(blue);

                    //红棋回到上一步
                    ModelList red1 = modelListMapRed.get(red)[0];
                    ModelList red2 = modelListMapRed.get(red)[1];
                    int posR1 = red1.getX() * 10 + red1.getY();
                    int posR2 = red2.getX() * 10 + red2.getY();
                    list.set(posR1, red1);
                    list.set(posR2, red2);
                    myAdapter.notifyItemChanged(posR1);
                    myAdapter.notifyItemChanged(posR2);
                    modelListMapRed.remove(red);

                    //恢复到红棋先走
                    isMove = false;
                }
            } else {

            }
        }
    }

    /**
     * 复制一个ModelList实体类
     *
     * @param modelList
     * @return
     */
    private ModelList getModelList(ModelList modelList) {
        ModelList model = new ModelList();
        model.setMapImage(modelList.getMapImage());
        model.setPieceImage(modelList.getPieceImage());
        model.setPieces(modelList.getPieces());
        model.setPieceType(modelList.getPieceType());
        model.setX(modelList.getX());
        model.setY(modelList.getY());
        return model;
    }

}
